using System;
using System.Net;
using System.Xml;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace NAnt.Microsoft.CRM.ThirdParty.Tasks
{
    [TaskName("crmcustexport")]
    public class ExportCustomisationsTask : Task
    {

        [TaskAttribute("crmserver", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string CrmServer { get; set; }

        [TaskAttribute("username", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Username { get; set; }

        [TaskAttribute("password", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Password { get; set; }

        [TaskAttribute("domain", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Domain { get; set; }

        [TaskAttribute("file", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string ExportFile { get; set; }

        [TaskAttribute("org", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Organisation { get; set; }

        [TaskAttribute("port", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Port { get; set; }

        protected override void ExecuteTask()
        {

            Project.Log(Level.Info, "Creating Connection");

            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = Organisation;

            CrmService crmservice = new CrmService();
            crmservice.Url = String.Format("http://{0}:{1}/mscrmservices/2007/crmservice.asmx", CrmServer, Port);
            crmservice.Credentials = new NetworkCredential(Username, Password, Domain);
            crmservice.CrmAuthenticationTokenValue = token;

            Export(crmservice);

        }

        public void Export(CrmService service)
        {

            Project.Log(Level.Info, "About to export");

            ExportAllXmlRequest request = new ExportAllXmlRequest();
            ExportAllXmlResponse response = (ExportAllXmlResponse)service.Execute(request);

            Project.Log(Level.Info, "Export completed");

            XmlDocument document = new XmlDocument();
            document.LoadXml(response.ExportXml);

            document.Save(ExportFile);

            Project.Log(Level.Info, "Export data saved");

        }
    }
}